package com.lm.curator.example;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

public class DistributedLockExample {
    public static void main(String[] args) throws Exception {
        // 初始化 CuratorFramework
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();

        // 创建分布式锁
        InterProcessMutex lock = new InterProcessMutex(client, "/distributed-lock");

        // 尝试获取锁
        if (lock.acquire(10, TimeUnit.SECONDS)) {
            try {
                System.out.println("成功获取锁，执行任务...");
                Thread.sleep(5000); // 模拟任务
            } finally {
                lock.release();
                System.out.println("锁已释放");
            }
        } else {
            System.out.println("未能获取锁");
        }

        client.close();
    }
}